package com.feizhou.oauth.config;

import java.util.Arrays;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

/**
 * 描述该类- JPA
 *
 * @author zhoufei
 * @class: AuthorizationServer
 * @date 2020/10/28 21:26
 * @Verson 1.0 -2020/10/28 21:26
 * @see
 */

@Configuration
@EnableAuthorizationServer // 配置授权服务。
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
    
    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;
    @Autowired
    // 授权码服务
    private AuthorizationCodeServices authorizationCodeServices;
    @Autowired
    // 认证管理
    private AuthenticationManager authenticationManager;
    @Autowired
    // 令牌管理服务
    private AuthorizationServerTokenServices authorizationServerTokenServices;
    
    @Autowired
    // 令牌存储策略
    private TokenStore tokenStore;
    @Autowired
    // 客户端详情服务,也就是configure(ClientDetailsServiceConfigurer clients)方法
    private ClientDetailsService clientDetailsService;

    @Autowired
    // 加密方式
    private PasswordEncoder passwordEncoder;

    //将客户端信息存储到数据库
    @Bean
    public ClientDetailsService clientDetailsService(DataSource dataSource) {
        ClientDetailsService clientDetailsService = new JdbcClientDetailsService(dataSource);
        ((JdbcClientDetailsService) clientDetailsService).setPasswordEncoder(passwordEncoder);
        return clientDetailsService;
    }


    // 用来配置客户端详情服务
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //数据库配置
        clients.withClientDetails(clientDetailsService);
    }


//    // 用来配置客户端详情服务
//    @Override
//    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        // 这里是第三方合作用户的客户id，秘钥的配置
//        // 使用in-memory存储
//        clients.inMemory()
//                // client_id，用户账号
//                .withClient("c1")
//                // 客户端密钥
//                .secret(new BCryptPasswordEncoder().encode("secret"))
//                // 资源列表，资源标识
//                .resourceIds("res1")
//                // 授权类型（4种）
//                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit",
//                        "refresh_token")
//                // 客戶端允许的授权范围
//                .scopes("all")
//                // false跳转到授权页面，让用户点击授权，如果是true,相当于自动点击授权，就不跳转授权页面
//                .autoApprove(false)//
//                // 加上验证回调地址，返回授权码信息
//                .redirectUris("http://www.baidu.com");
//
//        // 如果有多个用户，配置多个客户详情
//        // .and().withClient()
//
//    }


    // 令牌管理服务
    @Bean
    public AuthorizationServerTokenServices tokenService() {
        DefaultTokenServices service = new DefaultTokenServices();
        service.setClientDetailsService(clientDetailsService);
        service.setSupportRefreshToken(true);// 支持刷新
        service.setTokenStore(tokenStore);// 令牌存储
        
        // 令牌增强
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        service.setTokenEnhancer(tokenEnhancerChain);
        
        service.setAccessTokenValiditySeconds(7200); // 令牌默认有效期2小时
        service.setRefreshTokenValiditySeconds(259200); // 刷新令牌默认有效期3天
        return service;
    }
    
    @Override
    // 用来配置令牌（token）的访问端点
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints
                // 指定认证管理器
                .authenticationManager(authenticationManager)
                // 授权码模式需要
                .authorizationCodeServices(authorizationCodeServices)
                // 令牌管理服务
                .tokenServices(authorizationServerTokenServices)
                // jwt格式Token
                .accessTokenConverter(accessTokenConverter)
                // 允许post提交
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }
    
//    @Bean
//    // 授权码服务器
//    public AuthorizationCodeServices authorizationCodeServices() {
//        // 授权码模式的授权码采用内存方式存储
//        return new InMemoryAuthorizationCodeServices();
//    }

    @Bean
    // 授权码服务器
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        //授权码模式的授权码采用数据库方式存储
        return new JdbcAuthorizationCodeServices(dataSource);
    }
    
    @Override
    // 用来配置令牌端点的安全约束,拦截规则
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        
        security
                // 提供公有密匙的端点，如果你使用JWT令牌的话, 允许
                .tokenKeyAccess("permitAll()")
                // oauth/check_token：用于资源服务访问的令牌解析端点，允许
                .checkTokenAccess("permitAll()")
                // 表单认证,申请令牌
                .allowFormAuthenticationForClients();
    }
    
}